/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2008-2011, Salzburg Research. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - Neither the name of the KiWi Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributor(s):
 *  sstroka
 *
 * File Info:
 *   User: sstroka
 *   Date: 2011/02/18
 *   Time: 10:18
 *
 * Project: KiWi2, kiwi-core module
 */

package kiwi.core.services.security;

import kiwi.core.api.security.TokenManagerService;
import kiwi.core.model.security.AccessToken;
import kiwi.core.model.security.RefreshToken;
import kiwi.core.model.user.KiWiUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import java.util.Date;
import java.util.HashMap;

/**
 * User: Stephanie Stroka
 * Date: 18.02.2011
 * Time: 10:18:00
 */
@Named("kiwi.core.tokenManagerService")
@ApplicationScoped
public class TokenManagerServiceImpl implements TokenManagerService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /* <accessToken_string, accessToken_entity> */
    private HashMap<String, AccessToken> accessTokens;

    /* <refreshToken_string, refreshToken_entity> */
    private HashMap<String, RefreshToken> refreshTokens;

    @PostConstruct    
    private void init() {
        accessTokens = new HashMap<String, AccessToken>();
        refreshTokens = new HashMap<String, RefreshToken>(); 
    }

    /**
     * relates the accessToken with its expiration time, its refreshToken and the user
     * @param user
     * @param accessToken
     * @param refreshToken
     * @param expiration
     * @return
     */
    @Override
    public boolean setToken(KiWiUser user, String accessToken, String refreshToken, int expiration) {

        if(expiration < 0) {
            // evil!!!
            return false;
        }

        long currentMs = System.currentTimeMillis();
        long expirationMs = currentMs + (expiration * 1000);
        Date expirationDate = new Date(expirationMs);

        if(accessTokens.containsKey(accessToken)) {
            if(accessTokens.get(accessToken).getKiwiUser() != user) {
                log.error("AccessToken is already in use by another user.");
                return false;
            } else {
                log.warn("AccessToken already exists for current user. Ignoring token request.");
                return true;
            }
        }

        AccessToken accessTokenEntity = new AccessToken(accessToken, user, expirationDate);
        RefreshToken refreshTokenEntity = new RefreshToken(refreshToken, accessTokenEntity);
        
        accessTokens.put(accessToken, accessTokenEntity);
        refreshTokens.put(refreshToken, refreshTokenEntity);

        return true;
    }


    /**
     * getRefreshToken() returns a refreshTokenEntity if the refreshToken could be found
     * @param refreshToken
     * @return a refreshTokenEntity if the refreshToken could be found
     */
    @Override
    public RefreshToken getRefreshToken(String refreshToken) {
        if(!refreshTokens.containsKey(refreshToken)) {
            log.error("RefreshToken not found.");
            return null;
        } else {
            return refreshTokens.get(refreshToken);
        }
    }

    @Override
    public boolean removeAccessToken(String accessToken) {
        return accessTokens.remove(accessToken) == null ? true : false;
    }

    @Override
    public boolean removeRefreshToken(String refreshToken) {
        return refreshTokens.remove(refreshToken) == null ? true : false;
    }

    @Override
    public KiWiUser validateAccessToken(String accessToken) {
        if(!accessTokens.containsKey(accessToken)) {
            return null;
        }
        AccessToken accessTokenEntity = accessTokens.get(accessToken);
        Date expirationDate = accessTokenEntity.getExpirationDate();
        long currentMs = System.currentTimeMillis();

        if(expirationDate.getTime() < currentMs) {
            return null;
        } else {
            return accessTokenEntity.getKiwiUser();
        }
    }
}
